package com.gulimall.member.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gulimall.common.to.AuthSocialUserTo;
import com.gulimall.common.utils.PageUtils;
import com.gulimall.common.utils.Query;
import com.gulimall.member.dao.MemberDao;
import com.gulimall.member.entity.MemberEntity;
import com.gulimall.member.exception.PhoneExistsException;
import com.gulimall.member.exception.UsernameExistsException;
import com.gulimall.member.service.MemberLevelService;
import com.gulimall.member.service.MemberService;
import com.gulimall.member.vo.MemberLoginVo;
import com.gulimall.member.vo.MemberRegisterVo;
import com.gulimall.member.vo.OAuthGiteeUserVo;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.scrypt.SCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.net.HttpURLConnection;
import java.util.Date;
import java.util.Map;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {
    @Autowired
    private MemberLevelService levelService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>());

        return new PageUtils(page);
    }

    @Override
    public void registerMember(MemberRegisterVo registerVo) {
        MemberEntity memberEntity = new MemberEntity();
        //校验用户名是否被使用
        checkMemberUsername(registerVo.getUsername());
        //校验手机号是否被使用
        checkMemberPhone(registerVo.getPhone());
        //获取默认的会员等级
        Long levelId = levelService.getDefaultLevelId();

        memberEntity.setUsername(registerVo.getUsername());
        memberEntity.setMobile(registerVo.getPhone());
        memberEntity.setLevelId(levelId);
        memberEntity.setNickname(registerVo.getUsername());

        //spring家的密码编码器
        SCryptPasswordEncoder cryptPasswordEncoder = new SCryptPasswordEncoder();
        memberEntity.setPassword(cryptPasswordEncoder.encode(registerVo.getPassword()));
        memberEntity.setCreateTime(new Date());

        save(memberEntity);
    }

    @Override
    public void checkMemberPhone(String phone) throws PhoneExistsException {
        long mobileCount = count(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (mobileCount > 0) {
            throw new PhoneExistsException();
        }
    }

    @Override
    public void checkMemberUsername(String username) throws UsernameExistsException {
        long mobileCount = count(new QueryWrapper<MemberEntity>().eq("username", username));
        if (mobileCount > 0) {
            throw new UsernameExistsException();
        }
    }

    @Override
    public MemberEntity loginMember(MemberLoginVo loginVo) {
        MemberEntity memberEntity =
                getOne(new QueryWrapper<MemberEntity>().eq("username", loginVo.getUsername()).or().eq("mobile",
                        loginVo.getUsername()).or().eq("email", loginVo.getUsername()));
        if (memberEntity == null) {
            return null;
        }
        SCryptPasswordEncoder passwordEncoder = new SCryptPasswordEncoder();
        boolean matches = passwordEncoder.matches(loginVo.getPassword(), memberEntity.getPassword());
        return matches ? memberEntity : null;
    }

    @Override
    public MemberEntity oAuthLogin(AuthSocialUserTo socialUserTo) {
        MemberEntity memberEntity = null;
        //根据accessToken从gitee获取用户信息
        try {
            OkHttpClient client = new OkHttpClient.Builder().build();
            Request request = new Request.Builder().get().url(String.format("https://gitee" + ".com/api/v5/user" +
                    "?access_token=%s", socialUserTo.getAccessToken())).build();

            Response response = client.newCall(request).execute();
            if (response.code() == HttpURLConnection.HTTP_OK) {
                String userInfoJson = response.body().string();
                OAuthGiteeUserVo giteeUserVo =
                        JSONObject.parseObject(userInfoJson).to(new TypeReference<OAuthGiteeUserVo>() {
                        });
                //根据gitee的id判断当前gitee账户是否在本数据库中是否存储
                memberEntity = getOne(new QueryWrapper<MemberEntity>().eq("social_uid", giteeUserVo.getId()));
                if (memberEntity == null) {
                    memberEntity = new MemberEntity();
                    memberEntity.setSocialUid(giteeUserVo.getId().toString());
                    memberEntity.setAccessToken(socialUserTo.getAccessToken());
                    memberEntity.setExpiresIn(socialUserTo.getExpiresIn().toString());
                    memberEntity.setNickname(giteeUserVo.getName());
                    memberEntity.setLevelId(levelService.getDefaultLevelId());
                    memberEntity.setCreateTime(new Date());

                    save(memberEntity);
                } else {
                    memberEntity.setAccessToken(socialUserTo.getAccessToken());
                    memberEntity.setExpiresIn(socialUserTo.getExpiresIn().toString());

                    updateById(memberEntity);
                }
            } else {

            }
        } catch (Exception e) {
            log.error("获取gitee用户信息异常 " + e.getMessage());
        }

        return memberEntity;
    }

}
